<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author: 当燃
 * Date: 2015-09-09
 */
namespace Admin\Controller;
use Admin\Logic\OrderLogic;
use Think\AjaxPage;

class OrderController extends BaseController {
	
	public $order_status;
	public $pay_status;
	public $shipping_status;
	/*
	 * 初始化操作
	 */
	public function _initialize() {
		parent::_initialize();
		C('TOKEN_ON', false);
		// 关闭表单令牌验证
		$this -> order_status = C('ORDER_STATUS');
		$this -> pay_status = C('PAY_STATUS');
		$this -> shipping_status = C('SHIPPING_STATUS');
		// 订单 支付 发货状态
		$this -> assign('order_status', $this -> order_status);
		$this -> assign('pay_status', $this -> pay_status);
		$this -> assign('shipping_status', $this -> shipping_status);
	}

	/*
	 *订单首页
	 */
	public function index() {
		$begin = date('Y/m/d', (time() - 30 * 60 * 60 * 24));
		//30天前
		$end = date('Y/m/d', strtotime('+1 days'));
		$this -> assign('timegap', $begin . '-' . $end);
		$this -> display();
	}

	/*
	 *Ajax首页
	 */
	public function ajaxindex() {
		$orderLogic = new OrderLogic();
		$timegap = I('timegap');
		if ($timegap) {
			$gap = explode('-', $timegap);
			$begin = strtotime($gap[0]);
			$end = strtotime($gap[1]);
		}
		// 搜索条件
		$condition = array();
		I('consignee') ? $condition['consignee'] = trim(I('consignee')) : false;
		if ($begin && $end) {
			$condition['add_time'] = array('between', "$begin,$end");
		}
		I('order_sn') ? $condition['order_sn'] = trim(I('order_sn')) : false;
		I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
		I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
		I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;
		I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
		I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;

		// 分配工序
		I('allot_status') != '' ? $condition['allot_status'] = I('allot_status') : false;

		// 查看角色id 如果是超级管理员能操作分配订单
		$admin_info = getAdminInfo(session('admin_id'));

		$sort_order = I('order_by', 'DESC') . ' ' . I('sort');
		$count = M('order') -> where($condition) -> count();
		$Page = new AjaxPage($count, 15);
		//  搜索条件下 分页赋值
		foreach ($condition as $key => $val) {
			$Page -> parameter[$key] = urlencode($val);
		}
		$show = $Page -> show();
		

		//刷新订单时候更改 订单状态 方法和用户者页面一样
		$results = D('order');

		$orderList2 = $orderLogic -> getOrderList($condition, $sort_order, $Page -> firstRow, $Page -> listRows);
		//查询order的微企id字符串判断是否存在订单里面  存在保存结果1 否则保存0；
		$small = D('small_order');
		foreach ($orderList2 as $k => $v) {
			$order_sn = $v['order_sn'];
			$sql = "select * from ty_small_order where order_sn = '{$order_sn}'";
			$smallarr = $small -> query($sql);
			$i = 0;
			foreach ($smallarr as $k => $v3) {//already_offer
				if ($v3['allot_status'] == 2 && $v3['audit'] == 1) {
					$i++;
				}
			}

			if ($i == count($smallarr) && $i != 0 && $v['already_offer'] != 2 && $v['already_offer'] != 4) {

				$arr = array('already_offer' => 1);
				$results -> where("order_sn = '{$order_sn}'") -> save($arr);
			}
			if ($v['already_offer'] != 4) {
				foreach ($smallarr as $k => $v2) {//already_offer
					if ($v2['jiaqian'] != 0) {
						$arr = array('already_offer' => 2);
						$results -> where("order_sn = '{$order_sn}'") -> save($arr);
					}
				}
			}
			$qian = $results -> where("order_sn = '{$order_sn}'") -> field('total_amount') -> select();

			if ($qian[0]['total_amount'] != 0 && $v['already_offer'] != 4) {

				$arr = array('already_offer' => 3);

				$results -> where("order_sn = '{$order_sn}'") -> save($arr);
			}
		}
		//获取订单列表
		$orderList = $orderLogic -> getOrderList($condition, $sort_order, $Page -> firstRow, $Page -> listRows);
		//查询order的微企id字符串判断是否存在订单里面  存在保存结果1 否则保存0；
		//		$orderList = $small -> query($sql);\
	
		$order = D('small_order');
		$fpgx = D('fpgx');
		$gx = D('gx');
		$processing_state =D("processing_state");
		$weiqi_id = $admin_info['admin_id'];
		foreach ($orderList as $key => $v) {
			//判断加工情况 
			 $sn = $v['order_sn'];
			$psarr = $processing_state ->where("order_sn = '{$sn}' and inspection = 0 ") ->find();
			if($psarr){
				$orderList[$key]['psarr']= 0;//加工未完成 
			}else{
				$orderList[$key]['psarr']= 1;//加工完成待发货
			}

			
			$sql = "select * from ty_small_order , ty_users where ty_small_order.user_id = ty_users.user_id and order_sn = '{$sn}'";
			$orderList1 = $small -> query($sql);
			foreach ($orderList1 as $key => $v) {

				//查询判断订单工序的报价情况，如果全部都有报价则返回2保存到订单allot_statut 里面 2对应微企已报价
				$fpgxsql = "select id,shuliang from ty_fpgx where dingdan = {$v["order_sn"]} and tuhao ='{$v['chart_number']}'";
				$fpgx_arr = $fpgx -> query($fpgxsql);
				$gxsql = "select count(status) from ty_gx where fpgxid = '{$fpgx_arr[0]['id']}'";
				if ($v['allot_status'] == 1) {//先判断是否订单是否已经分配工序
					$gxsql = $gx -> query($gxsql);
					if ($fpgx_arr[0]["shuliang"] == $gxsql[0]['count(status)']) {
						$data['allot_status'] = 2;
						$order -> where("order_sn={$v["order_sn"]} and chart_number ='{$v['chart_number']}' ") -> save($data);
						// 根据条件更新记录
					}
					//    上面实现判断工序报价状况下面实现判断微企对这个订单有没有报价已经报价为1否则为0
				}
				$orderList[$key]["wq_id"] = 0;
				$source = $v['weiqi_id'];
				$sourcearr = explode(',', $source);
				foreach ($sourcearr as $v) {
					if ($v == $weiqi_id) {
						$orderList[$key]["wq_id"] = 1;
					}
				}

			}
		}
		// 20180 1 11 判断订单已选择图号里面是否存在当前登录的微企

		$weiqi_name = $admin_info['company_name'];
		$chart_price = D('chart_price');

		foreach ($orderList as $k => $v) {
			$order_sn = $v['order_sn'];
			$sql = "select id  from ty_chart_price where  order_sn = '{$order_sn}' and qiyename = '{$weiqi_name}' and judge_choose = 1 ";
			$arr = $chart_price -> query($sql);

			foreach ($arr as $arrv) {
				if ($arrv['id'] != null) {

					$orderList[$k]['bb'] = 1;
				} else {
					$orderList[$k]['bb'] = 0;
				}

			}
		}
		//		foreach ($orderList as $k => $v) {
		//			$order_sn = $v['order_sn'];
		//
		//			if ($v['bb'] == 1) {
		//				$smalllist = $small -> where("order_sn = '{$order_sn}' ") -> select();
		//
		//				foreach ($smalllist as $k2 => $v2) {
		//
		//					if ($v2['judge_choose'] = 1) {
		//						$ok = 1;
		//
		//					}
		//				}
		//				if ($ok != 1) {
		//					$orderList[$k]['bb'] = 0;
		//				}
		//			}
		//		}

		$this -> assign('admin_info', $admin_info);
		$this -> assign('page', $show);
		$this -> assign('orderList', $orderList);
		// 赋值分页输出
		$this -> display();
	}

	/*
	 * ajax 发货订单列表
	 */
	public function ajaxdelivery() {

		$orderLogic = new OrderLogic();
		$condition = array();
		I('consignee') ? $condition['consignee'] = trim(I('consignee')) : false;
		I('order_sn') != '' ? $condition['order_sn'] = trim(I('order_sn')) : false;
		$shipping_status = I('shipping_status');

		$condition['shipping_status'] = empty($shipping_status) ? array('eq', 0) : $shipping_status;
		// $condition['order_status'] = array('in', '1,2,4');
		$condition['pay_s_jj']  = array('in','2,3');
		$count = M('order') -> where($condition) -> count();
		$Page = new AjaxPage($count,10);
		//搜索条件下 分页赋值
		foreach ($condition as $key => $val) {
			$Page -> parameter[$key] = urlencode($val);
		}
		$show = $Page -> show();
		$orderList = M('order') -> where($condition) -> limit($Page -> firstRow . ',' . $Page -> listRows) -> order('add_time DESC') -> select();
		$this -> assign('orderList', $orderList);
		$this -> assign('page', $show);
		// 赋值分页输出
		$this -> display();
	}

	/**
	 * 订单详情
	 * @param $order_id 是图号
	 */
	public function detail($order_id, $order_sn) {

		$orderLogic = new OrderLogic();
		$order = $orderLogic -> getOrderInfo($order_sn);
		$orderGoods = $orderLogic -> getOrderGoods($order_sn);
		$button = $orderLogic -> getOrderButton($order);
		// 获取操作记录
		$action_log = M('order_action') -> where(array('order_sn' => $order_sn)) -> order('log_time desc') -> select();
		$this -> assign('action_log', $action_log);
		$this -> assign('orderGoods', $orderGoods);
		$split = count($orderGoods) > 1 ? 1 : 0;
		foreach ($orderGoods as $val) {
			if ($val['goods_num'] > 1) {
				$split = 1;
			}
		}

		// 自定义基本信息
		$order_base_info = D('small_order');
		$dingdan = $order_base_info -> query("select *  from ty_small_order , ty_users where ty_small_order.user_id = ty_users.user_id
		and order_sn='{$order_sn}' and chart_number = '{$order_id}'");
		$this -> assign('order_info', $dingdan);

		//  查看角色id 只要管理员才能看见 各微企报价
		$admin_info = getAdminInfo(session('admin_id'));
		$admin_id = $admin_info['admin_id'];
		$admin_name = $admin_info['user_name'];
		//分配工序显示
		$fpgx = D('fpgx');
		$fpgxarr = $fpgx -> query("SELECT chart_number,ty_gx.name,ty_gx.id FROM ty_fpgx,ty_small_order,ty_gx WHERE ty_fpgx.dingdan =ty_small_order.order_sn AND ty_fpgx.id = ty_gx.fpgxid 
		AND ty_small_order.order_sn = {$order_sn} and chart_number = '{$order_id}' and tuhao= '{$order_id}' ");

		//报价显示。。。做判断 微企只能看自己的报价情况，管理员Admin能看全部报价

		$baojia = D('baojia');
		//$dingdan = $order_base_info  ->query("select order_sn FROM ty_order where order_id = {$order_id}");

		$dinggdan = $order_sn;
		// $dingdan[0]['order_sn'];
		if ($admin_id == 1) {
			$baojia_info = $baojia -> query("SELECT ty_gx.id,ty_baojia.qiyename,ty_baojia.jiaqian FROM `ty_baojia`,ty_gx,ty_fpgx  WHERE ty_baojia.gxid = ty_gx.id and ty_gx.fpgxid=ty_fpgx.id 
		AND ty_fpgx.dingdan  = {$dinggdan}  and tuhao= '{$order_id}' ORDER BY ty_gx.id");

		} else {
			$baojia_info = $baojia -> query("SELECT ty_gx.id,ty_baojia.qiyename,ty_baojia.jiaqian FROM `ty_baojia`,ty_gx,ty_fpgx  WHERE ty_baojia.gxid = ty_gx.id and ty_gx.fpgxid=ty_fpgx.id AND ty_fpgx.dingdan  = {$dinggdan} 
		 AND ty_baojia.qiyename ='{$admin_name}' and tuhao= '{$order_id}'  ORDER BY ty_gx.id");

		}

		$this -> assign('baojia', $baojia_info);
		$this -> assign('fpgx', $fpgxarr);
		$this -> assign('split', $split);
		$this -> assign('button', $button);
		//图片文件的显示
		$sql = "select * FROM ty_small_order,ty_users WHERE ty_small_order.user_id = ty_users.user_id AND chart_number = '{$order_id}' and order_sn ='{$order_sn}'";

		$order = D('small_order') -> query($sql);

		$this -> assign('order', $order);
		$attachmentarr = $order[0]['image'];
		$attachmentarr = str_replace('./', '/', $attachmentarr);
		$attachment = explode(',', $attachmentarr);
		$i = 0;
		$j = 0;
		$k = 0;
		foreach ($attachment as $key => $v) {
			$str = explode('.', $v);
			if ($str[1] == 'jpg' || $str[1] == 'png') {
				$tupian[$i] = $v;
				$i = $i + 1;
			} else {

				$wenjian[$j][$str[1]] = $v;
				$j = $j + 1;
			}
		}
		
		$this -> assign('tupian', $tupian);
		$this -> assign('wenjian', $wenjian);
		$this -> assign('admin_id', $admin_id);
		$this -> display();

	}

	/**
	 * 订单编辑
	 * @param int $id 订单id
	 */
	public function edit_order() {
		$order_id = I('order_id');
		$orderLogic = new OrderLogic();
		$order = $orderLogic -> getOrderInfo($order_id);
		if ($order['shipping_status'] != 0) {
			$this -> error('已发货订单不允许编辑');
			exit ;
		}

		$orderGoods = $orderLogic -> getOrderGoods($order_id);

		if (IS_POST) {
			$order['consignee'] = I('consignee');
			// 收货人
			$order['province'] = I('province');
			// 省份
			$order['city'] = I('city');
			// 城市
			$order['district'] = I('district');
			// 县
			$order['address'] = I('address');
			// 收货地址
			$order['mobile'] = I('mobile');
			// 手机
			$order['invoice_title'] = I('invoice_title');
			// 发票
			$order['admin_note'] = I('admin_note');
			// 管理员备注
			$order['admin_note'] = I('admin_note');
			//
			$order['shipping_code'] = I('shipping');
			// 物流方式
			$order['shipping_name'] = M('plugin') -> where(array('status' => 1, 'type' => 'shipping', 'code' => I('shipping'))) -> getField('name');
			$order['pay_code'] = I('payment');
			// 支付方式
			$order['pay_name'] = M('plugin') -> where(array('status' => 1, 'type' => 'payment', 'code' => I('payment'))) -> getField('name');
			$goods_id_arr = I("goods_id");
			$new_goods = $old_goods_arr = array();
			//################################订单添加商品
			if ($goods_id_arr) {
				$new_goods = $orderLogic -> get_spec_goods($goods_id_arr);
				foreach ($new_goods as $key => $val) {
					$val['order_id'] = $order_id;
					$rec_id = M('order_goods') -> add($val);
					//订单添加商品
					if (!$rec_id)
						$this -> error('添加失败');
				}
			}

			//################################订单修改删除商品
			$old_goods = I('old_goods');
			foreach ($orderGoods as $val) {
				if (empty($old_goods[$val['rec_id']])) {
					M('order_goods') -> where("rec_id=" . $val['rec_id']) -> delete();
					//删除商品
				} else {
					//修改商品数量
					if ($old_goods[$val['rec_id']] != $val['goods_num']) {
						$val['goods_num'] = $old_goods[$val['rec_id']];
						M('order_goods') -> where("rec_id=" . $val['rec_id']) -> save(array('goods_num' => $val['goods_num']));
					}
					$old_goods_arr[] = $val;
				}
			}

			$goodsArr = array_merge($old_goods_arr, $new_goods);
			$result = calculate_price($order['user_id'], $goodsArr, $order['shipping_code'], 0, $order['province'], $order['city'], $order['district'], 0, 0, 0, 0);
			if ($result['status'] < 0) {
				$this -> error($result['msg']);
			}

			//################################修改订单费用
			$order['goods_price'] = $result['result']['goods_price'];
			// 商品总价
			$order['shipping_price'] = $result['result']['shipping_price'];
			//物流费
			$order['order_amount'] = $result['result']['order_amount'];
			// 应付金额
			$order['total_amount'] = $result['result']['total_amount'];
			// 订单总价
			$o = M('order') -> where('order_id=' . $order_id) -> save($order);

			$l = $orderLogic -> orderActionLog($order_id, 'edit', '修改订单');
			//操作日志
			if ($o && $l) {
				$this -> success('修改成功', U('Admin/Order/editprice', array('order_id' => $order_id)));
			} else {
				$this -> success('修改失败', U('Admin/Order/detail', array('order_id' => $order_id)));
			}
			exit ;
		}
		// 获取省份
		$province = M('region') -> where(array('parent_id' => 0, 'level' => 1)) -> select();
		//获取订单城市
		$city = M('region') -> where(array('parent_id' => $order['province'], 'level' => 2)) -> select();
		//获取订单地区
		$area = M('region') -> where(array('parent_id' => $order['city'], 'level' => 3)) -> select();
		//获取支付方式
		$payment_list = M('plugin') -> where(array('status' => 1, 'type' => 'payment')) -> select();
		//获取配送方式
		$shipping_list = M('plugin') -> where(array('status' => 1, 'type' => 'shipping')) -> select();

		$this -> assign('order', $order);
		$this -> assign('province', $province);
		$this -> assign('city', $city);
		$this -> assign('area', $area);
		$this -> assign('orderGoods', $orderGoods);
		$this -> assign('shipping_list', $shipping_list);
		$this -> assign('payment_list', $payment_list);
		$this -> display();
	}

	/*
	 * 拆分订单
	 */
	public function split_order() {
		$order_id = I('order_id');
		$orderLogic = new OrderLogic();
		$order = $orderLogic -> getOrderInfo($order_id);
		if ($order['shipping_status'] != 0) {
			$this -> error('已发货订单不允许编辑');
			exit ;
		}
		$orderGoods = $orderLogic -> getOrderGoods($order_id);
		if (IS_POST) {
			$data = I('post.');
			//################################先处理原单剩余商品和原订单信息
			$old_goods = I('old_goods');
			foreach ($orderGoods as $val) {
				if (empty($old_goods[$val['rec_id']])) {
					M('order_goods') -> where("rec_id=" . $val['rec_id']) -> delete();
					//删除商品
				} else {
					//修改商品数量
					if ($old_goods[$val['rec_id']] != $val['goods_num']) {
						$val['goods_num'] = $old_goods[$val['rec_id']];
						M('order_goods') -> where("rec_id=" . $val['rec_id']) -> save(array('goods_num' => $val['goods_num']));
					}
					$oldArr[] = $val;
					//剩余商品
				}
				$all_goods[$val['rec_id']] = $val;
				//所有商品信息
			}
			$result = calculate_price($order['user_id'], $oldArr, $order['shipping_code'], 0, $order['province'], $order['city'], $order['district'], 0, 0, 0, 0);
			if ($result['status'] < 0) {
				$this -> error($result['msg']);
			}
			//修改订单费用
			$res['goods_price'] = $result['result']['goods_price'];
			// 商品总价
			$res['order_amount'] = $result['result']['order_amount'];
			// 应付金额
			$res['total_amount'] = $result['result']['total_amount'];
			// 订单总价
			M('order') -> where("order_id=" . $order_id) -> save($res);
			//################################原单处理结束

			//################################新单处理
			for ($i = 1; $i < 20; $i++) {
				if (!empty($_POST[$i . '_old_goods'])) {
					$split_goods[] = $_POST[$i . '_old_goods'];
				}
			}

			foreach ($split_goods as $key => $vrr) {
				foreach ($vrr as $k => $v) {
					$all_goods[$k]['goods_num'] = $v;
					$brr[$key][] = $all_goods[$k];
				}
			}

			foreach ($brr as $goods) {
				$result = calculate_price($order['user_id'], $goods, $order['shipping_code'], 0, $order['province'], $order['city'], $order['district'], 0, 0, 0, 0);
				if ($result['status'] < 0) {
					$this -> error($result['msg']);
				}
				$new_order = $order;
				$new_order['order_sn'] = date('YmdHis') . mt_rand(1000, 9999);
				$new_order['parent_sn'] = $order['order_sn'];
				//修改订单费用
				$new_order['goods_price'] = $result['result']['goods_price'];
				// 商品总价
				$new_order['order_amount'] = $result['result']['order_amount'];
				// 应付金额
				$new_order['total_amount'] = $result['result']['total_amount'];
				// 订单总价
				$new_order['add_time'] = time();
				unset($new_order['order_id']);
				$new_order_id = M('order') -> add($new_order);
				//插入订单表
				foreach ($goods as $vv) {
					$vv['order_id'] = $new_order_id;
					unset($vv['rec_id']);
					$nid = M('order_goods') -> add($vv);
					//插入订单商品表
				}
			}
			//################################新单处理结束
			$this -> success('操作成功', U('Admin/Order/detail', array('order_id' => $order_id)));
			exit ;
		}

		foreach ($orderGoods as $val) {
			$brr[$val['rec_id']] = array('goods_num' => $val['goods_num'], 'goods_name' => getSubstr($val['goods_name'], 0, 35) . $val['spec_key_name']);
		}
		$this -> assign('order', $order);
		$this -> assign('goods_num_arr', json_encode($brr));
		$this -> assign('orderGoods', $orderGoods);
		$this -> display();
	}

	/*
	 * 价钱修改
	 */
	public function editprice($order_id) {
		$orderLogic = new OrderLogic();
		$order = $orderLogic -> getOrderInfo($order_id);
		$this -> editable($order);
		if (IS_POST) {
			$admin_id = session('admin_id');
			if (empty($admin_id)) {
				$this -> error('非法操作');
				exit ;
			}
			$update['discount'] = I('post.discount');
			$update['shipping_price'] = I('post.shipping_price');
			$update['order_amount'] = $order['goods_price'] + $update['shipping_price'] - $update['discount'] - $order['user_money'] - $order['integral_money'] - $order['coupon_price'];
			$row = M('order') -> where(array('order_id' => $order_id)) -> save($update);
			if (!$row) {
				$this -> success('没有更新数据', U('Admin/Order/editprice', array('order_id' => $order_id)));
			} else {
				$this -> success('操作成功', U('Admin/Order/detail', array('order_id' => $order_id)));
			}
			exit ;
		}
		$this -> assign('order', $order);
		$this -> display();
	}

	/**
	 * 订单删除
	 * @param int $id 订单id
	 */
	public function delete_order($order_id) {
		$orderLogic = new OrderLogic();
		$del = $orderLogic -> delOrder($order_id);
		if ($del) {
			$this -> success('删除订单成功');
		} else {
			$this -> error('订单删除失败');
		}
	}

	/**
	 * 订单取消付款
	 */
	public function pay_cancel($order_id) {
		if (I('remark')) {
			$data = I('post.');
			$note = array('退款到用户余额', '已通过其他方式退款', '不处理，误操作项');
			if ($data['refundType'] == 0 && $data['amount'] > 0) {
				accountLog($data['user_id'], $data['amount'], 0, '退款到用户余额');
			}
			$orderLogic = new OrderLogic();
			$orderLogic -> orderProcessHandle($data['order_id'], 'pay_cancel');
			$d = $orderLogic -> orderActionLog($data['order_id'], 'pay_cancel', $data['remark'] . ':' . $note[$data['refundType']]);
			if ($d) {
				exit("<script>window.parent.pay_callback(1);</script>");
			} else {
				exit("<script>window.parent.pay_callback(0);</script>");
			}
		} else {
			$order = M('order') -> where("order_id=$order_id") -> find();
			$this -> assign('order', $order);
			$this -> display();
		}
	}

	/**
	 * 订单打印
	 * @param int $id 订单id
	 */
	public function order_print() {
		$order_id = I('order_id');
		$orderLogic = new OrderLogic();
		$order = $orderLogic -> getOrderInfo($order_id);
		$order['province'] = getRegionName($order['province']);
		$order['city'] = getRegionName($order['city']);
		$order['district'] = getRegionName($order['district']);
		$order['full_address'] = $order['province'] . ' ' . $order['city'] . ' ' . $order['district'] . ' ' . $order['address'];
		$orderGoods = $orderLogic -> getOrderGoods($order_id);
		$shop = tpCache('shop_info');
		//传递图号信息
		$small_order = M("small_order");
		$orderss = M("order");
		$order_sn = $orderss -> where("order_id ={$order_id} ") -> field('order_sn') -> find();	
		$small_orderarr = $small_order -> where("order_sn = {$order_sn['order_sn']} and judge_choose = 1 ") ->select();
		
		$this -> assign('small_orderarr',$small_orderarr);
		$this -> assign('order', $order);
		$this -> assign('shop', $shop);
		$this -> assign('orderGoods', $orderGdeoods);
		$template = I('template', 'print');
		$this -> display($template);
	}

	/**
	 * 快递单打印
	 */
	public function shipping_print() {
		$order_id = I('get.order_id');
		$orderLogic = new OrderLogic();
		$order = $orderLogic -> getOrderInfo($order_id);
		//查询是否存在订单及物流
		$shipping = M('plugin') -> where(array('code' => $order['shipping_code'], 'type' => 'shipping')) -> find();
		if (!$shipping) {
			$this -> error('物流插件不存在');
		}
		if (empty($shipping['config_value'])) {
			$this -> error('请设置' . $shipping['name'] . '打印模板');
		}
		$shop = tpCache('shop_info');
		//获取网站信息
		$shop['province'] = empty($shop['province']) ? '' : getRegionName($shop['province']);
		$shop['city'] = empty($shop['city']) ? '' : getRegionName($shop['city']);
		$shop['district'] = empty($shop['district']) ? '' : getRegionName($shop['district']);

		$order['province'] = getRegionName($order['province']);
		$order['city'] = getRegionName($order['city']);
		$order['district'] = getRegionName($order['district']);
		if (empty($shipping['config'])) {
			$config = array('width' => 840, 'height' => 480, 'offset_x' => 0, 'offset_y' => 0);
			$this -> assign('config', $config);
		} else {
			$this -> assign('config', unserialize($shipping['config']));
		}
		$template_var = array("发货点-名称", "发货点-联系人", "发货点-电话", "发货点-省份", "发货点-城市", "发货点-区县", "发货点-手机", "发货点-详细地址", "收件人-姓名", "收件人-手机", "收件人-电话", "收件人-省份", "收件人-城市", "收件人-区县", "收件人-邮编", "收件人-详细地址", "时间-年", "时间-月", "时间-日", "时间-当前日期", "订单-订单号", "订单-备注", "订单-配送费用");
		$content_var = array($shop['store_name'], $shop['contact'], $shop['phone'], $shop['province'], $shop['city'], $shop['district'], $shop['phone'], $shop['address'], $order['consignee'], $order['mobile'], $order['phone'], $order['province'], $order['city'], $order['district'], $order['zipcode'], $order['address'], date('Y'), date('M'), date('d'), date('Y-m-d'), $order['order_sn'], $order['admin_note'], $order['shipping_price'], );
		$shipping['config_value'] = str_replace($template_var, $content_var, $shipping['config_value']);
		$this -> assign('shipping', $shipping);
		$this -> display("Plugin/print_express");
	}

	/**
	 * 生成发货单
	 */
	public function deliveryHandle() {
		$orderLogic = new OrderLogic();
		$data = I('post.');
		
		
		// $res = $orderLogic -> deliveryHandle($data);
		// if ($res) {
		// 	$this -> success('操作成功', U('Admin/Order/delivery_info', array('order_id' => $data['order_id'])));
		// } else {
		// 	$this -> success('操作失败', U('Admin/Order/delivery_info', array('order_id' => $data['order_id'])));
		// }
		//20180329 jj的发货单
		$admin_info = getAdminInfo(session('admin_id'));
		
		$admin_id = $admin_info['admin_id'];
		$j =time();
		$delivery_doc = D("delivery_doc");
		$order  = D("order");
		$orderarr = $order -> where("order_id = {$data['order_id']}") ->find();
		$arr = array('order_id' =>  $data['order_id'] ,
						'order_sn' =>  $orderarr['order_sn'] ,
						'user_id' =>  $orderarr['user_id'] ,
						'admin_id' =>  $admin_id ,
						'consignee' =>  $orderarr['consignee'] ,
						'mobile' =>  $orderarr['mobile'] ,
						'province' =>  $orderarr['jj_provinces'] ,
						'city' =>  $orderarr['jj_city'] ,
						'district' =>  $orderarr['jj_area'] ,
						'address' =>  $orderarr['address'] ,
						'shipping_name' =>  $data['shipping_name'] ,
						'invoice_no' =>  $data['invoice_no'] ,
						'note' =>  $data['note'] ,
						'create_time' =>  $j ,


					);

		$res = $delivery_doc ->add($arr);
		$a =array('shipping_status' => 1,
					'shipping_name' =>$data['shipping_name']);
		$id = $order -> where("order_id = {$data['order_id']}") ->save($a);
		if ($res && $id) {

		 	$this -> success('操作成功', U('Admin/Order/delivery_info', array('order_id' => $data['order_id'])));
		 } else {
		 	$this -> success('操作失败', U('Admin/Order/delivery_info', array('order_id' => $data['order_id'])));
		 }

	}
	//自提方式
	public function delivery_ziti(){
		$order_id = I('order_id');
		$order = D('order');
		$arr = array('shipping_status' =>2 );
		$id = $order -> where("order_id = {$order_id}") ->save($arr);
	if($id){
		
		$this -> success('操作成功', U('Admin/Order/delivery_list'));
	}

	}
	public function delivery_info() {
		$order_id = I('order_id');
		$orderLogic = new OrderLogic();
		$order = $orderLogic -> getOrderInfo($order_id);
		$orderGoods = $orderLogic -> getOrderGoods($order_id);
		$delivery_record = M('delivery_doc') -> join('LEFT JOIN __ADMIN__ ON __ADMIN__.admin_id = __DELIVERY_DOC__.admin_id') -> where('order_id=' . $order_id) -> select();
		// dump($delivery_record);
		if ($delivery_record) {
			$order['invoice_no'] = $delivery_record[count($delivery_record) - 1]['invoice_no'];
		}
		//订单图号信息
		$small_order = M("small_order");
		$orderss = M("order");
		$order_sn = $orderss -> where("order_id ={$order_id} ") -> field('order_sn') -> find();	
		$small_orderarr = $small_order -> where("order_sn = {$order_sn['order_sn']} and judge_choose = 1 ") ->select();
		
		$this -> assign('small_orderarr',$small_orderarr);
		$this -> assign('order', $order);
		$this -> assign('orderGoods', $orderGoods);
		$this -> assign('delivery_record', $delivery_record);
		//发货记录
		$this -> display();
	}

	/**
	 * 发货单列表
	 */
	public function delivery_list() {
		$this -> display();
	}

	/*
	 * ajax 退货订单列表
	 */
	public function ajax_return_list() {
		// 搜索条件
		$order_sn = trim(I('order_sn'));
		$order_by = I('order_by') ? I('order_by') : 'id';
		$sort_order = I('sort_order') ? I('sort_order') : 'desc';
		$status = I('status');

		$where = " 1 = 1 ";
		$order_sn && $where .= " and order_sn like '%$order_sn%' ";
		empty($order_sn) && $where .= " and status = '$status' ";
		$count = M('return_goods') -> where($where) -> count();
		$Page = new AjaxPage($count, 13);
		$show = $Page -> show();
		$list = M('return_goods') -> where($where) -> order("$order_by $sort_order") -> limit("{$Page->firstRow},{$Page->listRows}") -> select();
		$goods_id_arr = get_arr_column($list, 'goods_id');
		if (!empty($goods_id_arr))
			$goods_list = M('goods') -> where("goods_id in (" . implode(',', $goods_id_arr) . ")") -> getField('goods_id,goods_name');
		$this -> assign('goods_list', $goods_list);
		$this -> assign('list', $list);
		$this -> assign('page', $show);
		// 赋值分页输出
		$this -> display();
	}

	/**
	 * 删除某个退换货申请
	 */
	public function return_del() {
		$id = I('get.id');
		M('return_goods') -> where("id = $id") -> delete();
		$this -> success('成功删除!');
	}

	/**
	 * 退换货操作
	 */
	public function return_info() {
		$id = I('id');
		$return_goods = M('return_goods') -> where("id= $id") -> find();
		if ($return_goods['imgs'])
			$return_goods['imgs'] = explode(',', $return_goods['imgs']);
		$user = M('users') -> where("user_id = {$return_goods[user_id]}") -> find();
		$goods = M('goods') -> where("goods_id = {$return_goods[goods_id]}") -> find();
		$type_msg = array('退换', '换货');
		$status_msg = array('未处理', '处理中', '已完成');
		if (IS_POST) {
			$data['type'] = I('type');
			$data['status'] = I('status');
			$data['remark'] = I('remark');
			$note = "退换货:{$type_msg[$data['type']]}, 状态:{$status_msg[$data['status']]},处理备注：{$data['remark']}";
			$result = M('return_goods') -> where("id= $id") -> save($data);
			if ($result) {
				$type = empty($data['type']) ? 2 : 3;
				$where = " order_id = " . $return_goods['order_id'] . " and goods_id=" . $return_goods['goods_id'];
				M('order_goods') -> where($where) -> save(array('is_send' => $type));
				//更改商品状态
				$orderLogic = new OrderLogic();
				$log = $orderLogic -> orderActionLog($return_goods[order_id], 'refund', $note);
				$this -> success('修改成功!');
				exit ;
			}
		}

		$this -> assign('id', $id);
		// 用户
		$this -> assign('user', $user);
		// 用户
		$this -> assign('goods', $goods);
		// 商品
		$this -> assign('return_goods', $return_goods);
		// 退换货
		$this -> display();
	}

	/**
	 * 管理员生成申请退货单
	 */
	public function add_return_goods() {
		$order_id = I('order_id');
		$goods_id = I('goods_id');

		$return_goods = M('return_goods') -> where("order_id = $order_id and goods_id = $goods_id") -> find();
		if (!empty($return_goods)) {
			$this -> error('已经提交过退货申请!', U('Admin/Order/return_list'));
			exit ;
		}
		$order = M('order') -> where("order_id = $order_id") -> find();

		$data['order_id'] = $order_id;
		$data['order_sn'] = $order['order_sn'];
		$data['goods_id'] = $goods_id;
		$data['addtime'] = time();
		$data['user_id'] = $order[user_id];
		$data['remark'] = '管理员申请退换货';
		// 问题描述
		M('return_goods') -> add($data);
		$this -> success('申请成功,现在去处理退货', U('Admin/Order/return_list'));
		exit ;
	}

	/**
	 * 订单操作
	 * @param $id
	 */
	public function order_action() {
		$orderLogic = new OrderLogic();
		$action = I('get.type');
		$order_id = I('get.order_id');
		if ($action && $order_id) {
			$a = $orderLogic -> orderProcessHandle($order_id, $action);
			$res = $orderLogic -> orderActionLog($order_id, $action, I('note'));
			if ($res && $a) {
				exit(json_encode(array('status' => 1, 'msg' => '操作成功')));
			} else {
				exit(json_encode(array('status' => 0, 'msg' => '操作失败')));
			}
		} else {
			$this -> error('参数错误', U('Admin/Order/detail', array('order_id' => $order_id)));
		}
	}

	public function order_log() {
		$timegap = I('timegap');
		if ($timegap) {
			$gap = explode('-', $timegap);
			$begin = strtotime($gap[0]);
			$end = strtotime($gap[1]);
		}
		$condition = array();
		$log = M('order_action');
		if ($begin && $end) {
			$condition['log_time'] = array('between', "$begin,$end");
		}
		$admin_id = I('admin_id');
		if ($admin_id > 0) {
			$condition['action_user'] = $admin_id;
		}
		$count = $log -> where($condition) -> count();
		$Page = new \Think\Page($count, 20);
		foreach ($condition as $key => $val) {
			$Page -> parameter[$key] = urlencode($val);
		}
		$show = $Page -> show();
		$list = $log -> where($condition) -> order('action_id desc') -> limit($Page -> firstRow . ',' . $Page -> listRows) -> select();
		$this -> assign('list', $list);
		$this -> assign('page', $show);
		$admin = M('admin') -> getField('admin_id,user_name');
		$this -> assign('admin', $admin);
		$this -> display();
	}

	/**
	 * 检测订单是否可以编辑
	 * @param $order
	 */
	private function editable($order) {
		if ($order['shipping_status'] != 0) {
			$this -> error('已发货订单不允许编辑');
			exit ;
		}
		return;
	}

	public function export_order() {
		//搜索条件
		$where = 'where 1=1 ';
		$consignee = I('consignee');
		if ($consignee) {
			$where .= " AND consignee like '%$consignee%' ";
		}
		$order_sn = I('order_sn');
		if ($order_sn) {
			$where .= " AND order_sn = '$order_sn' ";
		}
		if (I('order_status')) {
			$where .= " AND order_status = " . I('order_status');
		}

		$timegap = I('timegap');
		if ($timegap) {
			$gap = explode('-', $timegap);
			$begin = strtotime($gap[0]);
			$end = strtotime($gap[1]);
			$where .= " AND add_time>$begin and add_time<$end ";
		}

		$sql = "select *,FROM_UNIXTIME(add_time,'%Y-%m-%d') as create_time from __PREFIX__order $where order by order_id";
		$orderList = D() -> query($sql);
		$strTable = '<table width="500" border="1">';
		$strTable .= '<tr>';
		$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">订单编号</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="100">日期</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货人</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货地址</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">电话</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单金额</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">实际支付</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付方式</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付状态</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">发货状态</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品信息</td>';
		$strTable .= '</tr>';
		if (is_array($orderList)) {
			$region = M('region') -> getField('id,name');
			foreach ($orderList as $k => $val) {
				$strTable .= '<tr>';
				$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;' . $val['order_sn'] . '</td>';
				$strTable .= '<td style="text-align:left;font-size:12px;">' . $val['create_time'] . ' </td>';
				$strTable .= '<td style="text-align:left;font-size:12px;">' . $val['consignee'] . '</td>';
				$strTable .= '<td style="text-align:left;font-size:12px;">' . "{$region[$val['province']]},{$region[$val['city']]},{$region[$val['district']]},{$region[$val['twon']]}{$val['address']}" . ' </td>';
				$strTable .= '<td style="text-align:left;font-size:12px;">' . $val['mobile'] . '</td>';
				$strTable .= '<td style="text-align:left;font-size:12px;">' . $val['goods_price'] . '</td>';
				$strTable .= '<td style="text-align:left;font-size:12px;">' . $val['order_amount'] . '</td>';
				$strTable .= '<td style="text-align:left;font-size:12px;">' . $val['pay_name'] . '</td>';
				$strTable .= '<td style="text-align:left;font-size:12px;">' . $this -> pay_status[$val['pay_status']] . '</td>';
				$strTable .= '<td style="text-align:left;font-size:12px;">' . $this -> shipping_status[$val['shipping_status']] . '</td>';
				$orderGoods = D('order_goods') -> where('order_id=' . $val['order_id']) -> select();
				$strGoods = "";
				foreach ($orderGoods as $goods) {
					$strGoods .= "商品编号：" . $goods['goods_sn'] . " 商品名称：" . $goods['goods_name'];
					if ($goods['spec_key_name'] != '')
						$strGoods .= " 规格：" . $goods['spec_key_name'];
					$strGoods .= "<br />";
				}
				unset($orderGoods);
				$strTable .= '<td style="text-align:left;font-size:12px;">' . $strGoods . ' </td>';
				$strTable .= '</tr>';
			}
		}
		$strTable .= '</table>';
		unset($orderList);
		downloadExcel($strTable, 'order');
		exit();
	}

	/**
	 * 退货单列表
	 */
	public function return_list() {
		$this -> display();
	}

	/**
	 * 添加一笔订单
	 */
	public function add_order() {
		$order = array();
		//  获取省份
		$province = M('region') -> where(array('parent_id' => 0, 'level' => 1)) -> select();
		//  获取订单城市
		$city = M('region') -> where(array('parent_id' => $order['province'], 'level' => 2)) -> select();
		//  获取订单地区
		$area = M('region') -> where(array('parent_id' => $order['city'], 'level' => 3)) -> select();
		//  获取配送方式
		$shipping_list = M('plugin') -> where(array('status' => 1, 'type' => 'shipping')) -> select();
		//  获取支付方式
		$payment_list = M('plugin') -> where(array('status' => 1, 'type' => 'payment')) -> select();
		if (IS_POST) {
			$order['user_id'] = I('user_id');
			// 用户id 可以为空
			$order['consignee'] = I('consignee');
			// 收货人
			$order['province'] = I('province');
			// 省份
			$order['city'] = I('city');
			// 城市
			$order['district'] = I('district');
			// 县
			$order['address'] = I('address');
			// 收货地址
			$order['mobile'] = I('mobile');
			// 手机
			$order['invoice_title'] = I('invoice_title');
			// 发票
			$order['admin_note'] = I('admin_note');
			// 管理员备注
			$order['order_sn'] = date('YmdHis') . mt_rand(1000, 9999);
			// 订单编号;
			$order['admin_note'] = I('admin_note');
			//
			$order['add_time'] = time();
			//
			$order['shipping_code'] = I('shipping');
			// 物流方式
			$order['shipping_name'] = M('plugin') -> where(array('status' => 1, 'type' => 'shipping', 'code' => I('shipping'))) -> getField('name');
			$order['pay_code'] = I('payment');
			// 支付方式
			$order['pay_name'] = M('plugin') -> where(array('status' => 1, 'type' => 'payment', 'code' => I('payment'))) -> getField('name');

			$goods_id_arr = I("goods_id");
			$orderLogic = new OrderLogic();
			$order_goods = $orderLogic -> get_spec_goods($goods_id_arr);
			$result = calculate_price($order['user_id'], $order_goods, $order['shipping_code'], 0, $order[province], $order[city], $order[district], 0, 0, 0, 0);
			if ($result['status'] < 0) {
				$this -> error($result['msg']);
			}

			$order['goods_price'] = $result['result']['goods_price'];
			// 商品总价
			$order['shipping_price'] = $result['result']['shipping_price'];
			//物流费
			$order['order_amount'] = $result['result']['order_amount'];
			// 应付金额
			$order['total_amount'] = $result['result']['total_amount'];
			// 订单总价

			// 添加订单
			$order_id = M('order') -> add($order);
			if ($order_id) {
				foreach ($order_goods as $key => $val) {
					$val['order_id'] = $order_id;
					$rec_id = M('order_goods') -> add($val);
					if (!$rec_id)
						$this -> error('添加失败');
				}
				$this -> success('添加商品成功', U("Admin/Order/detail", array('order_id' => $order_id)));
				exit();
			} else {
				$this -> error('添加失败');
			}
		}
		$this -> assign('shipping_list', $shipping_list);
		$this -> assign('payment_list', $payment_list);
		$this -> assign('province', $province);
		$this -> assign('city', $city);
		$this -> assign('area', $area);
		$this -> display();
	}

	/**
	 * 选择搜索商品
	 */
	public function search_goods() {
		$brandList = M("brand") -> select();
		$categoryList = M("goods_category") -> select();
		$this -> assign('categoryList', $categoryList);
		$this -> assign('brandList', $brandList);
		$where = ' is_on_sale = 1 ';
		//搜索条件
		I('intro') && $where = "$where and " . I('intro') . " = 1";
		if (I('cat_id')) {
			$this -> assign('cat_id', I('cat_id'));
			$grandson_ids = getCatGrandson(I('cat_id'));
			$where = " $where  and cat_id in(" . implode(',', $grandson_ids) . ") ";
			// 初始化搜索条件

		}
		if (I('brand_id')) {
			$this -> assign('brand_id', I('brand_id'));
			$where = "$where and brand_id = " . I('brand_id');
		}
		if (!empty($_REQUEST['keywords'])) {
			$this -> assign('keywords', I('keywords'));
			$where = "$where and (goods_name like '%" . I('keywords') . "%' or keywords like '%" . I('keywords') . "%')";
		}
		$goodsList = M('goods') -> where($where) -> order('goods_id DESC') -> limit(10) -> select();

		foreach ($goodsList as $key => $val) {
			$spec_goods = M('spec_goods_price') -> where("goods_id = {$val['goods_id']}") -> select();
			$goodsList[$key]['spec_goods'] = $spec_goods;
		}
		$this -> assign('goodsList', $goodsList);
		$this -> display();
	}

	public function ajaxOrderNotice() {
		//$order_amount = M('order')->where("order_status=0 and (pay_status=1 or pay_code='cod')")->count();
		$order_amount = M('order') -> where("order_status=0") -> count();
		echo $order_amount;
	}

	//进入分配工序页面并显示
	//	public function fpgx($order_id){
	//		//$sql = "select attachment, order_id,order_sn,user_name,ty_users.mobile,ptype,add_time FROM ty_order,ty_users WHERE ty_order.user_id = ty_users.user_id AND order_id = {$order_id} ";
	//		$sql = "select * FROM ty_order,ty_users WHERE ty_order.user_id = ty_users.user_id AND order_id = {$order_id} ";
	//
	//		$order = D('order')->query($sql);
	//
	//		$attachmentarr = $order[0]['attachment'];
	//		$attachmentarr= str_replace('./', '/', $attachmentarr);
	//		$attachment=explode(',',$attachmentarr);
	//		$i = 0;
	//		$j = 0;
	//		$k = 0;
	//		foreach($attachment as $key => $v){
	//          $str = explode('.',$v);
	//			if($str[1]=='jpg' || $str[1]=='png'){
	//				$tupian[$i] = $v;
	//				$i=$i+1;
	//			}else{
	//
	//				$wenjian[$j][$str[1]]=$v;
	//				$j=$j+1;
	//			}
	//		}
	//		$this->assign('tupian',$tupian);
	//		$this->assign('wenjian',$wenjian);
	//		$this->assign('order',$order);
	//		$this->display();
	//	}
	public function fpgx($order_id, $order_sn) {//$order_id 是图号
		//$sql = "select attachment, order_id,order_sn,user_name,ty_users.mobile,ptype,add_time FROM ty_order,ty_users WHERE ty_order.user_id = ty_users.user_id AND order_id = {$order_id} ";
		$sql = "select * FROM ty_small_order,ty_users WHERE ty_small_order.user_id = ty_users.user_id AND chart_number = '{$order_id}' and order_sn ='{$order_sn}'";

		$order = D('small_order') -> query($sql);

		$attachmentarr = $order[0]['image'];
		$attachmentarr = str_replace('./', '/', $attachmentarr);
		$attachment = explode(',', $attachmentarr);
		$i = 0;
		$j = 0;
		$k = 0;
		foreach ($attachment as $key => $v) {
			$str = explode('.', $v);
			if ($str[1] == 'jpg' || $str[1] == 'png') {
				$tupian[$i] = $v;
				$i = $i + 1;
			} else {

				$wenjian[$j][$str[1]] = $v;
				$j = $j + 1;
			}
		}
		$this -> assign('tupian', $tupian);
		$this -> assign('wenjian', $wenjian);
		$this -> assign('order', $order);
		$this -> display();
	}

	//获取分配好的工序写入数据库
	//	public function gxbc(){
	//
	//		$i = 0;
	//		if($_POST){
	//			$gxsl = $_POST;
	//			//print_r($gxsl);
	//		foreach($gxsl as $v){
	//			if(is_numeric($v)){
	//				if($v<=32 ){
	//					$shuliang = $v;
	//				}else{
	//					$bianhao = $v;
	//					//print_r($v);
	//				}
	//			}else{
	//				$gxarr[$i]=$v;
	//				$i =$i+1;
	//			}
	//		}
	//		$result = D('fpgx');
	//		$arr = array(
	//		'shuliang' => $shuliang,
	//		'dingdan'  => $bianhao,
	//		);
	//
	//	$id  =	$result ->add($arr);
	//		if($id){
	//		$gx = D('gx');
	//		foreach($gxarr as $v){
	//			$arr = array(
	//				'name' => $v,
	//				'fpgxid' => $id ,
	//			);
	//		$gxid = 	$gx  ->add($arr);
	//			}
	//			}
	//		if($gxid){
	//			print_r("ok");
	//			$order = D('order');
	//			$data['allot_status']= 1;
	//			$order->where("order_sn={$bianhao}")->save($data); // 根据条件更新记录
	//
	//		}
	//
	//		}
	//
	//	}
	//获取分配好的工序写入数据库
	public function gxbc() {

		$i = 0;
		if ($_POST) {
			$gxsl = $_POST;

			foreach ($gxsl as $k => $v) {
				if ($k != "order_sn" && $k != "order_chartNumber" && !is_numeric($v)) {
					$gxarr[$i] = $v;
					$i = $i + 1;
				}
			}
			print_r($gxarr);
			$result = D('fpgx');
			$arr = array('shuliang' => $_POST['gxsl'], 'dingdan' => $_POST['order_sn'], 'tuhao' => $_POST['order_chartNumber']);

			$id = $result -> add($arr);
			if ($id) {
				$gx = D('gx');
				foreach ($gxarr as $v) {
					$arr = array('name' => $v, 'fpgxid' => $id, );
					$gxid = $gx -> add($arr);
				}
			}
			if ($gxid) {
			
				$order = D('small_order');
				$data['allot_status'] = 1;
				$order -> where("order_sn='{$_POST['order_sn']}' AND chart_number ='{$_POST['order_chartNumber']}' ") -> save($data);
				// 根据条件更新记录
				//分配工序后判断是否全部图号已经分配工序
				$smallarr = $order -> where("order_sn='{$_POST['order_sn']}' ") -> select();
				$s = $order -> where("order_sn='{$_POST['order_sn']}' ") -> count();
				$i = 0;
				foreach ($smallarr as $v) {
					if ($v['allot_status'] != 0) {
						$i++;
					}
				}
				if ($i == $s) {
					$or = D('order');
					$order_status = array('order_status' => 1);

					$or -> where("order_sn='{$_POST['order_sn']}' ") -> save($order_status);
				} elseif ($i != 0) {
					$or = D('order');
					$order_status = array('order_status' => 2);

					$or -> where("order_sn='{$_POST['order_sn']}' ") -> save($order_status);
				}
			}

		}

	}

	//进入报价页面 展示
	//	public function gxbj($order_id){
	public function gxbj($order_sn, $chart_number) {
		$small = D('small_order');

		$dingdan = $small -> query("select * from ty_small_order , ty_users where ty_small_order.user_id = ty_users.user_id
		and order_sn='{$order_sn}' and ty_small_order.chart_number = '{$chart_number}'");

		$bianhao = $order_sn;
		$result = D('fpgx');
		$gxzs = $result -> query("SELECT ty_gx.id,name,fpgxid,shuliang,dingdan,tuhao FROM ty_gx,ty_fpgx WHERE ty_gx.fpgxid=ty_fpgx.id AND ty_fpgx.dingdan = {$order_sn} AND ty_fpgx.tuhao ='{$chart_number}' ");
		$this -> assign('gxzs', $gxzs);
		$this -> assign('order', $dingdan);
		//图片文件的显示

		$sql = "select * FROM ty_small_order,ty_users WHERE ty_small_order.user_id = ty_users.user_id AND chart_number = '{$chart_number}' and order_sn ='{$order_sn}'";

		$order = D('small_order') -> query($sql);
		$this -> assign('order', $order);
		$attachmentarr = $order[0]['image'];
		$attachmentarr = str_replace('./', '/', $attachmentarr);
		$attachment = explode(',', $attachmentarr);
		$i = 0;
		$j = 0;
		$k = 0;
		foreach ($attachment as $key => $v) {
			$str = explode('.', $v);
			if ($str[1] == 'jpg' || $str[1] == 'png') {
				$tupian[$i] = $v;
				$i = $i + 1;
			} else {

				$wenjian[$j][$str[1]] = $v;
				$j = $j + 1;
			}
		}
		$this -> assign('tupian', $tupian);
		$this -> assign('wenjian', $wenjian);
		$this -> display();

	}

	//保存报价数据到数据库
	public function bcbj() {

		if ($_POST) {
			$bjarr = $_POST;

			foreach ($bjarr as $key => $v) {//拆分数据保存数据库
				if ($key == 'company_name') {
					$qiyename = $v;
				} else if ($key == 'order_number') {
					$bianhao = $v;
				} else if ($key == 'order_chartNumber') {
					$order_chartNumber = $v;
				} else {
					$arr[$key] = $v;
				}
			}

			$admin_info = getAdminInfo(session('admin_id'));
			$qiyename = $admin_info['user_name'];
			$weiqi_id = $admin_info['admin_id'];
			$gx = D('gx');
			$baojia = D('baojia');
			///保存报价微企的id数据到订单表
			$order = D("small_order");
			$orderarr = $order -> where("order_sn={$bianhao} and chart_number= '{$order_chartNumber}'") -> find();
			$weiqi = $orderarr['weiqi_id'];
			if ($weiqi == null) {
				$weiqi_info = $weiqi_id;
			} else {
				$weiqi_info = $weiqi . "," . $weiqi_id;
			}
			$data['weiqi_id'] = $weiqi_info;
			$order -> where("order_sn={$bianhao} and chart_number= '{$order_chartNumber}'") -> save($data);
			// 根据条件更新记录

			//遍历加载到数据库
			foreach ($arr as $key => $v) {
				if ($v != 0) {
					$baojiaarr = array('gxid' => $key, 'jiaqian' => $v, 'qiyename' => $qiyename, );
					$bjid = $baojia -> add($baojiaarr);
					$data['status'] = 1;
					$gx -> where("id={$key}") -> save($data);
					// 根据条件更新记录

				}

			}
		}

	}

	//	public  function edit_fpgx($order_id){
	//	$sql = "select * FROM ty_order,ty_users WHERE ty_order.user_id = ty_users.user_id AND order_id = {$order_id} ";
	//
	//		$order = D('order')->query($sql);
	//
	//		$attachmentarr = $order[0]['attachment'];
	//		$attachmentarr= str_replace('./', '/', $attachmentarr);
	//		$attachment=explode(',',$attachmentarr);
	//		$i = 0;
	//		$j = 0;
	//		$k = 0;
	//		foreach($attachment as $key => $v){
	//          $str = explode('.',$v);
	//			if($str[1]=='jpg' || $str[1]=='png'){
	//				$tupian[$i] = $v;
	//				$i=$i+1;
	//			}else{
	//
	//				$wenjian[$j][$str[1]]=$v;
	//				$j=$j+1;
	//			}
	//		}
	//		$this->assign('tupian',$tupian);
	//		$this->assign('wenjian',$wenjian);
	//		$this->assign('order',$order);
	//		$this->display();
	//}
	//新的图号显示
	public function edit_fpgx($order_id, $order_sn) {//$order_id 是图号
		//$sql = "select attachment, order_id,order_sn,user_name,ty_users.mobile,ptype,add_time FROM ty_order,ty_users WHERE ty_order.user_id = ty_users.user_id AND order_id = {$order_id} ";
		$sql = "select * FROM ty_small_order,ty_users WHERE ty_small_order.user_id = ty_users.user_id AND chart_number = '{$order_id}' and order_sn ='{$order_sn}'";

		$order = D('small_order') -> query($sql);
		$attachmentarr = $order[0]['image'];
		$attachmentarr = str_replace('./', '/', $attachmentarr);
		$attachment = explode(',', $attachmentarr);
		$i = 0;
		$j = 0;
		$k = 0;
		foreach ($attachment as $key => $v) {
			$str = explode('.', $v);
			if ($str[1] == 'jpg' || $str[1] == 'png') {
				$tupian[$i] = $v;
				$i = $i + 1;
			} else {

				$wenjian[$j][$str[1]] = $v;
				$j = $j + 1;
			}
		}
		$this -> assign('tupian', $tupian);
		$this -> assign('wenjian', $wenjian);
		$this -> assign('order', $order);
		$this -> display();
	}

	//先update fpgx表的数量字段  再级联删除 下面表的数据。 修改工序
	public function gx_update() {
		if ($_POST) {

			$fpgx = D('fpgx');

			$fpgx_id_arr = $fpgx -> query("select id from ty_fpgx where dingdan={$_POST[order_sn]} and tuhao='{$_POST[order_chartNumber]}'");
			$fp_id = $fpgx_id_arr[0][id];
			$data['shuliang'] = $_POST[gxsl];

			$fpgx -> where("id={$fp_id} and tuhao='{$_POST[order_chartNumber]}'") -> save($data);
			// 根据条件更新记录

			//删除报价
			$gx = D('gx');
			$bj = D("baojia");
			$gx_id_arr = $gx -> query("select id from ty_gx where fpgxid = {$fp_id}");
			foreach ($gx_id_arr as $v) {//遍历删除
				$gx_id = $v[id];
				$bj_fh = $bj -> query("delete from ty_baojia where gxid = {$gx_id}");

			}
			//删除工序表

			$gx_fanhui = $gx -> query("delete from ty_gx  where fpgxid = {$fp_id} ");
			//添加新数据

			$i = 0;

			foreach ($_POST as $v) {
				if (is_numeric($v)) {
					if ($v <= 32) {
						$shuliang = $v;
					} else {
						$bianhao = $v;

					}
				} else {
					$gxarr[$i] = $v;
					$i = $i + 1;
				}

			}

			foreach ($gxarr as $v) {
				$arr = array('name' => $v, 'fpgxid' => $fp_id, );
				$gxid = $gx -> add($arr);
				if ($gxid) {

					$results = D('order');
					$order = D('small_order');
					$data['allot_status'] = 1;
					$data2 = array('already_offer' => 0, 'total_amount' => 0);

					//订单状态
					//更新订单已经选择的报价。
					$results -> where("order_sn = '{$_POST[order_sn]}'") -> save($data2);
					$data['weiqi_id'] = null;
					//清空已经报价的微企ID
					$order -> where("order_sn={$bianhao} and chart_number = '{$_POST[order_chartNumber]}' ") -> save($data);
					// 根据条件更新记录
				}
			}
		}
	}

	public function edit_gxbj($order_id, $order_sn) {//$order_id 是图号
		$sql = "select * FROM ty_small_order,ty_users WHERE ty_small_order.user_id = ty_users.user_id AND chart_number = '{$order_id}' and order_sn ='{$order_sn}'";
		$order = D('small_order') -> query($sql);
		$this -> assign('order', $order);
		//  查看角色id 只要管理员才能看见 各微企报价
		$admin_info = getAdminInfo(session('admin_id'));
		$admin_id = $admin_info['admin_id'];
		$admin_name = $admin_info['user_name'];
		$baojia = D('baojia');
		$dinggdan = $order_sn;
		if ($admin_id == 1) {//管理员查看所有报价  微企只能看自己的报价
			$baojia_info = $baojia -> query("SELECT ty_gx.id,ty_baojia.qiyename,ty_baojia.jiaqian FROM `ty_baojia`,ty_gx,ty_fpgx  WHERE ty_baojia.gxid = ty_gx.id and ty_gx.fpgxid=ty_fpgx.id AND ty_fpgx.dingdan  = {$dinggdan}
		and tuhao ='{$order_id}' ORDER BY ty_gx.id");
		} else {
			$baojia_info = $baojia -> query("SELECT ty_gx.id,ty_baojia.qiyename,ty_baojia.jiaqian FROM `ty_baojia`,ty_gx,ty_fpgx  WHERE ty_baojia.gxid = ty_gx.id and ty_gx.fpgxid=ty_fpgx.id AND ty_fpgx.dingdan  = {$dinggdan} 
		AND ty_baojia.qiyename ='{$admin_name}' and tuhao = '{$order_id}'  ORDER BY ty_gx.id");
			$bianhao = $order_sn;
			$result = D('fpgx');
			$gxzs = $result -> query("SELECT ty_gx.id,name,fpgxid,shuliang,dingdan,tuhao FROM ty_gx,ty_fpgx WHERE ty_gx.fpgxid=ty_fpgx.id AND ty_fpgx.dingdan = {$order_sn} AND ty_fpgx.tuhao ='{$order_id}' ");
		}
		$this -> assign('gxzs', $gxzs);
		$this -> assign('baojia', $baojia_info);
		$this -> assign('admin_id', $admin_id);
		$this -> display();

	}

	//修改报价
	public function baojia_update() {
		if ($_POST) {

			$admin_info = getAdminInfo(session('admin_id'));
			$admin_id = $admin_info['admin_id'];
			$admin_name = $admin_info['user_name'];
			if ($admin_id == 1) {// 这个是admin

				$linst = $_POST;

				$baojia = D('baojia');

				//处理前段反馈数据转成有用数据
				$s = count($linst);
				//数组长度
				$baojia_gx = $s / 3;
				for ($i = 1; $i <= $baojia_gx; $i++) {//将前台返回的数据处理成想要的样子。
					$k = 'gxid' . $i;
					$compayname = 'compay_name' . $i;
					$compay_name = $linst[$compayname];
					$new_offer = 'new_offer' . $i;
					if ($linst[$new_offer] != null) {//有新报价才回进入
						$data = array('jiaqian' => $linst[$new_offer]);
						$baojia -> where("gxid = {$linst[$k]} and qiyename = '{$compay_name}'") -> save($data);
						// 根据条件更新记录
					}
				}
				echo 1;
			} else {// 这个是微企修改页面
				$baojia = D('baojia');

				$linst = $_POST;
				$gx = D('gx');
				//			$s = count($linst);
				$compay_name = $admin_name;
				$i = 1;
				foreach ($linst as $k => $v) {
					if ($v != null) {// 有新报价才进入
						$sql = "select * from ty_baojia where qiyename = '{$compay_name}' and gxid = {$k}";
						$id = $baojia -> query($sql);

						if ($id != null) {

							$data = array('jiaqian' => $v, 'qiyename' => $compay_name);
							$baojia -> where("gxid = {$k} and qiyename = '{$compay_name}'") -> save($data);
							// 根据条件更新记录
							$data['status'] = 1;
							$gx -> where("id={$k}") -> save($data);

						} else {
							$data = array('jiaqian' => $v, 'qiyename' => $compay_name, 'gxid' => $k);
							$baojia -> add($data);
							$data['status'] = 1;
							$gx -> where("id={$k}") -> save($data);
						}

					}
				}
				echo 1;
			}
		}

	}

	//操作订单后跳转回订单页面
	public function skip($order_sn) {
		$order = D('order');

		$id = $order -> where("order_sn = '{$order_sn}'") -> select();
		$id = $id[0]['order_id'];

		return $this -> redirect('tuhaolist', array('order_id' => $id), 1, '页面跳转中');
		//return $this -> success('提交成功', "index", 3);
	}

	// 图号的显示
	public function tuhaolist($order_id) {

		$sql = "select * FROM ty_order,ty_users WHERE ty_order.user_id = ty_users.user_id AND order_id = {$order_id} ";

		$order = D('order') -> query($sql);
		$small = D('small_order');
		$ordera = D('order') -> where("order_id = {$order_id}") ->select();
		$address['jj_province'] = $ordera[0]['jj_provinces'];
		$address['jj_city'] = $ordera[0]['jj_city'];
		$address['jj_region'] = $ordera[0]['jj_area'];
		$address['jj_post'] = $order[0]['jj_post'];
		$address['jj_user_phone'] = $ordera[0]['mobile'];
		$address['jj_receiver'] = $ordera[0]['consignee'];
		$address['jj_detail_address'] = $ordera[0]['address'];
		//传递订单支付信息
		$orderpay = D('order');
		if($order[0]['pay_s_jj'] == 1 or $order[0]['pay_s_jj'] == 4){//首款支付
			$payarr[0] = $orderpay ->where("order_id = {$order_id}") -> field('first_je,first_time,first_jy_sn,first_sn') ->find();
			$pararrs[0]['je'] = $payarr[0]['first_je'] ;
			$pararrs[0]['time'] = $payarr[0]['first_time'] ;
			$pararrs[0]['jy_sn'] = $payarr[0]['first_jy_sn'] ;
			$pararrs[0]['sn'] = $payarr[0]['first_sn'] ;
			$i = substr($pararrs[0]['jy_sn'], -1);
			if($i == 1 ){
				$pararrs[0]['pay_a'] = 1;
			}elseif($i == 2){
				$pararrs[0]['pay_a'] = 2;
			}
		
			$pararrs[0]['jy_sn']= substr($pararrs[0]['jy_sn'],0,strlen($pararrs[0]['jy_sn'])-1);
		}elseif($order[0]['pay_s_jj'] == 2 or $order[0]['pay_s_jj']  == 5){//全额
			$payarr[0] = $orderpay ->where("order_id = {$order_id}") -> field('in_full_je,in_full_time,in_full_jy_sn,in_full_sn') ->find();
			$pararrs[0]['je'] = $payarr[0]['in_full_je'] ;
			$pararrs[0]['time'] = $payarr[0]['in_full_time'] ;
			$pararrs[0]['jy_sn'] = $payarr[0]['in_full_jy_sn'] ;
			$pararrs[0]['sn'] = $payarr[0]['in_full_sn'] ;
			$i = substr($pararrs[0]['jy_sn'], -1);
			if($i == 1 ){
				$pararrs[0]['pay_a'] = 1;
			}elseif($i == 2){
				$pararrs[0]['pay_a'] = 2;
			}
			$pararrs[0]['jy_sn']= substr($pararrs[0]['jy_sn'],0,strlen($pararrs[0]['jy_sn'])-1);
		}elseif ($order[0]['pay_s_jj'] == 3 or $order[0]['pay_s_jj']  == 6) {//尾款
			$order_firstarr = $orderpay ->where("order_id = {$order_id}") -> field('first_je,first_time,first_jy_sn,first_sn') ->find();
			$tail_paragrapharr = $orderpay ->where("order_id = {$order_id}") -> field('tail_je,tail_time,tail_jy_sn,tail_sn') ->find();
			$pararrs[0]['je'] = $order_firstarr['first_je'] ;
			$pararrs[0]['time'] = $order_firstarr['first_time'] ;
			$pararrs[0]['jy_sn'] = $order_firstarr['first_jy_sn'] ;
			$pararrs[0]['sn'] = $order_firstarr['first_sn'] ;
			$pararrs[1]['je'] = $tail_paragrapharr['tail_je'] ;
			$pararrs[1]['time'] = $tail_paragrapharr['tail_time'] ;
			$pararrs[1]['jy_sn'] = $tail_paragrapharr['tail_jy_sn'] ;
			$pararrs[1]['sn'] = $tail_paragrapharr['tail_sn'] ;
			$i = substr($pararrs[0]['jy_sn'], -1);
			if($i == 1 ){
				$pararrs[0]['pay_a'] = 1;
			}elseif($i == 2){
				$pararrs[0]['pay_a'] = 2;
			}$i = substr($pararrs[1]['jy_sn'], -1);
			if($i == 1 ){
				$pararrs[1]['pay_a'] = 1;
			}elseif($i == 2){
				$pararrs[1]['pay_a'] = 2;
			}
	
			$pararrs[0]['jy_sn']= substr($pararrs[0]['jy_sn'],0,strlen($pararrs[0]['jy_sn'])-1);
			$pararrs[1]['jy_sn']= substr($pararrs[1]['jy_sn'],0,strlen($pararrs[1]['jy_sn'])-1);

		}
		// $order[0]['payarr'] = $order[0]['pay_a'] .",".$order[0]['pay_b'] ;
		 		
		$this -> assign('pararrs',$pararrs);
		$this -> assign('order', $order);
		//图号显示

		$admin_info = getAdminInfo(session('admin_id'));
		$sn = $order[0]['order_sn'];
		$sql = "select * from ty_small_order , ty_users where ty_small_order.user_id = ty_users.user_id and order_sn = '{$sn}'";
		$orderList = $small -> query($sql);

		//查询order的微企id字符串判断是否存在订单里面  存在保存结果1 否则保存0；
		$order = D('small_order');
		$fpgx = D('fpgx');
		$gx = D('gx');
		$weiqi_id = $admin_info['admin_id'];
		foreach ($orderList as $key => $v) {

			//查询判断订单工序的报价情况，如果全部都有报价则返回2保存到订单allot_statut 里面 2对应微企已报价
			$fpgxsql = "select id,shuliang from ty_fpgx where dingdan = {$v["order_sn"]} and tuhao ='{$v['chart_number']}'";
			$fpgx_arr = $fpgx -> query($fpgxsql);
			$gxsql = "select count(status) from ty_gx where fpgxid = '{$fpgx_arr[0]['id']}'";
			if ($v['allot_status'] == 1) {//先判断是否订单是否已经分配工序
				//print_r('进入已经分配工序的订单 ....');
				$gxsql = $gx -> query($gxsql);
				if ($fpgx_arr[0]["shuliang"] == $gxsql[0]['count(status)']) {
					//print_r($fpgx_arr[0]["shuliang"]);
					//print_r('进入已经报价的订单 ....');
					//print_r($gxsql[0]['count(status)']);
					$data['allot_status'] = 2;
					$order -> where("order_sn={$v["order_sn"]} and chart_number ='{$v['chart_number']}' ") -> save($data);
					// 根据条件更新记录
				}
				//    上面实现判断工序报价状况下面实现判断微企对这个订单有没有报价已经报价为1否则为0
			}
			$orderList[$key]["wq_id"] = 0;
			$source = $v['weiqi_id'];
			$sourcearr = explode(',', $source);
			foreach ($sourcearr as $v) {
				if ($v == $weiqi_id) {
					$orderList[$key]["wq_id"] = 1;
				}
			}

		}
		// 订单其他费用的显示
		$order_other = D('order_other');
		$order_otherarr = $order_other -> where(" order_sn = '{$sn}'") -> find();
		//20180 1 11 判断 图号里面是否存在当前登录的微企
		$weiqi_name = $admin_info['company_name'];
		$chart_price = D('chart_price');
	if($admin_info['admin_id'] == 1){
			$i = 0;
		foreach ($orderList as $k => $v) {
			$order_sn = $v['order_sn'];
			$chart_number = $v['chart_number'];
			$chart_numberarr[$i] =$chart_number; 
			$i++;
			$sql = "select id  from ty_chart_price where  order_sn = '{$order_sn}' and chart_number = '{$chart_number}'  and judge_choose = 1";
			$arr = $chart_price -> query($sql);

			if ($arr[0]['id'] != null) {
				$orderList[$k]['bb'] = 1;
			} else {
				$orderList[$k]['bb'] = 0;
			}
			
		}
	}else{
			$i = 0;
		foreach ($orderList as $k => $v) {
			$order_sn = $v['order_sn'];
			$chart_number = $v['chart_number'];
			$chart_numberarr[$i] =$chart_number; 
			$i++;
			$sql = "select id  from ty_chart_price where  order_sn = '{$order_sn}' and qiyename = '{$weiqi_name}' and chart_number = '{$chart_number}'  and judge_choose = 1";
			$arr = $chart_price -> query($sql);

			if ($arr[0]['id'] != null) {
				$orderList[$k]['bb'] = 1;
			} else {
				$orderList[$k]['bb'] = 0;
			}
			
		}
	}
		//处理
		$ordera = D("order");
		$smalla = D("small_order");
	    $ordera = $ordera ->where("order_sn = '{$order_sn}' ") -> find();
		$user_id = $ordera['user_id'];	
		$i = 0;
		foreach ($chart_numberarr as $value) {
			
		 $snarr[$i] = $smalla ->where("user_id = {$user_id} and chart_number = '{$value}'") -> field("order_sn,chart_number") -> select();
		 $i++;
		}
		$i = 0;
		foreach ($snarr as $sn) {
			foreach ($sn as $k => $value) {
				//print_r($value);
				if($value['order_sn'] != $order_sn){
					$snarrs[$i] = $value;
							$i++;			
				}
				
			}
			
		}
	 	
		$count=count($snarrs);
		for($i=0;$i<$count;$i++){
		for ($j=$i+1;$j<$count;$j++){
		if($snarrs[$i]['chart_number']==$snarrs[$j]['chart_number']){
		unset($snarrs[$j]);
		}
		}
		} 
		
		$this ->assign('snarr',$snarrs);
		$this ->assign('address',$address);
		$this -> assign('order_otherarr', $order_otherarr);
		$this -> assign('admin_info', $admin_info);

		$this -> assign('orderList', $orderList);

		$this -> assign('order_id', $order_id);
		

		$this -> display();
	}

	//图号审核
	public function audit() {
		if ($_POST) {

			$small = D('small_order');
			$arr = array('audit' => 1);
			$id = $small -> where("order_sn = '{$_POST['order_sn']}' and chart_number = '{$_POST['order_chartNumber']}'") -> save($arr);
			if ($id) {

				echo 1;
			}
		}
	}

	// 其他费用显示
	public function other_cost() {
		$other_expenses = D('other_expenses');
		$add = $other_expenses -> find();
		if ($add == null) {
			$s = -1;
			$this -> assign('s', $s);
		}

		$this -> assign('other_expenses_info', $add);
		$this -> display();
	}

	//增加其他费用比例ty_other_expenses
	public function add_otherCost() {
		if ($_POST) {
			$other_expenses = D('other_expenses');

			$add = array('technology' => $_POST['technology'], 'packaging' => $_POST['package'], 'management' => $_POST['manage'], 'transport' => $_POST['transport'], 'cycle' => $_POST['cycle'], 'detection' => $_POST['check'], 'tax' => $_POST['tax'], 'profits' => $_POST['profit']);

			$id = $other_expenses -> add($add);
			if ($id) {
				return $this -> success('提交成功', "other_cost", 3);
			}
		}
		$this -> display();
	}

	//更改其他费用比例
	public function edit_otherCost($id) {

		if ($_POST) {
			$other_expenses = D('other_expenses');
			$add = array('technology' => $_POST['technology'], 'packaging' => $_POST['package'], 'management' => $_POST['manage'], 'transport' => $_POST['transport'], 'cycle' => $_POST['cycle'], 'detection' => $_POST['check'], 'tax' => $_POST['tax'], 'profits' => $_POST['profit']);

			$s = $other_expenses -> where(" id = {$id}") -> save($add);
			if ($s) {
				return $this -> success('提交成功', U('Admin/Order/other_cost'), 3);
			}
		}
		$other_expenses = D('other_expenses');
		$add = $other_expenses -> where(" id = {$id}") -> find();
		$this -> assign('other_expenses_info', $add);
		$this -> display();
	}

	//更改订单费用比例
	public function edit_proportion($order_id) {
		$order = D('order');
		$orderlist = $order -> where("order_id = {$order_id}") -> find();
		if ($_POST) {

			$order_other = D('order_other');
			$add = array('technology' => $_POST['technology'], 'packaging' => $_POST['package'], 'management' => $_POST['manage'], 'transport' => $_POST['transport'], 'cycle' => $_POST['cycle'], 'detection' => $_POST['check'], 'tax' => $_POST['tax'], 'profits' => $_POST['profit'], 'judge' => 0);

			$s = $order_other -> where(" order_sn = '{$orderlist['order_sn']}'") -> save($add);
			if ($s) {
				return $this -> success('提交成功', U('Admin/Order/tuhaolist', array('order_id' => $order_id)), 3);
			}
		} else {
			$this -> assign('order_id', $order_id);
			$order_other = D('order_other');

			$add = $order_other -> where(" order_sn = '{$orderlist['order_sn']}'  and judge = 0 ") -> find();

			$this -> assign('other_expenses_info', $add);
			$this -> display();
		}

	}

	//更改订单费用金额
	public function input_money($order_id) {
		$order = D('order');
		$orderlist = $order -> where("order_id = {$order_id}") -> find();
		if ($_POST) {

			$order_other = D('order_other');
			$add = array('technology' => $_POST['technology'], 'packaging' => $_POST['package'], 'management' => $_POST['manage'], 'transport' => $_POST['transport'], 'cycle' => $_POST['cycle'], 'detection' => $_POST['check'], 'tax' => $_POST['tax'], 'profits' => $_POST['profit'], 'judge' => 1);

			$s = $order_other -> where(" order_sn = '{$orderlist['order_sn']}'") -> save($add);
			if ($s) {
				return $this -> success('提交成功', U('Admin/Order/tuhaolist', array('order_id' => $order_id)), 3);
			}
		} else {
			$this -> assign('order_id', $order_id);
			$order_other = D('order_other');

			$add = $order_other -> where(" order_sn = '{$orderlist['order_sn']}' and judge = 1") -> find();

			$this -> assign('other_expenses_info', $add);
			$this -> display();
		}

	}

	//被消费者选择消费的微企信息和工序完成状态
	public function select_companies($order_id, $order_sn) {//$order_id 是图号
		$admin_info = getAdminInfo(session('admin_id'));
		//获取登录者信息
		$weiqi_id = $admin_info['admin_id'];
		$qiyename = $admin_info['company_name'];
		$chart_price = D('chart_price');
		$processing_state = D('processing_state');
		$prolist = $processing_state -> where("chart_number = '{$order_id}' and order_sn = '{$order_sn}'") -> select();

		if ($prolist == null) {
			// if ($weiqi_id != 1) {
			// 	var_dump("sss");
			// 	$sql = "select ty_small_order.time_delivery,ty_small_order.remark,ty_chart_price.gx_name,ty_chart_price.qiyename from ty_chart_price, ty_small_order where ty_chart_price.chart_number = ty_small_order.chart_number 
			// 		and qiyename = '{$qiyename}' and ty_chart_price.order_sn = '{$order_sn}' and ty_chart_price.chart_number = '{$order_id}' and ty_chart_price.judge_choose = 1 ";
			// 	//	$chartlist = $chart_price -> where(" qiyename = '{$qiyename}' and order_sn = '{$order_sn}' and chart_number = '{$order_id}' ") -> select();
			// 	$chartlist = $chart_price -> query($sql);

			// } else {
			// 	$sql = "select ty_small_order.time_delivery,ty_small_order.remark,ty_chart_price.gx_name,ty_chart_price.qiyename from ty_chart_price, ty_small_order where ty_chart_price.chart_number = ty_small_order.chart_number 
			// 		 and ty_chart_price.order_sn = '{$order_sn}' and  ty_chart_price.chart_number = '{$order_id}' and ty_chart_price.judge_choose = 1 ";
			// 	$chartlist = $chart_price -> query($sql);
			// 	//$chartlist = $chart_price -> where("  order_sn = '{$order_sn}' and chart_number = '{$order_id}' ") -> select();

			// }
			// // 将图号 , 订单号 补充到 chartList
			// foreach ($chartlist as $k => $value) {
			// 	$chartlist[$k] = $value;
			// 	$chartlist[$k]['order_sn'] = $order_sn;
			// 	$chartlist[$k]['figure_number'] = $order_id;
			// };

			// foreach ($chartlist as $k => $value) {
			// 	$arr = array('order_sn' => $value['order_sn'], 'chart_number' => $value['figure_number'], 'qiyename' => $value['qiyename'], 'gx_name' => $value['gx_name'], 'state' => 0, 'remark' => $value['remark'], 'time_delivery' => $value['time_delivery']);
			// 	$processing_state -> add($arr);
			// }

		} else {
			if($weiqi_id != 1){
			$prolist = $processing_state -> where("chart_number = '{$order_id}' and order_sn = '{$order_sn}' and qiyename = '{$qiyename}'") -> select();
			$chartlist = $prolist;
			foreach ($prolist as $k => $v) {
				$chartlist[$k]['figure_number'] = $v['chart_number'];
			}
			}else{
				$prolist = $processing_state -> where("chart_number = '{$order_id}' and order_sn = '{$order_sn}' ") -> select();
				$chartlist = $prolist;
				foreach ($prolist as $k => $v) {
					$chartlist[$k]['figure_number'] = $v['chart_number'];
						}
				}
		

		}
				//20180323
				$i=0;
				foreach ($chartlist as $key => $value) {
					if($value['state'] == 2){
						$i++;
					}
				}
				$i == count($chartlist) ? $q = 1 : $q=0;
				$small_order = D('small_order');
				$inspectionarr = $small_order -> where("chart_number = '{$order_id}'") -> find();
				$inspection = $inspectionarr['inspection'];
				//print_r($chartlist);
		$this -> assign('q', $q);//判读加工状态
		$this -> assign('inspection',$inspection);//判断检验结果
		$this -> assign('chartlist', $chartlist);
		$this -> assign('admin_info', $admin_info);
		$this -> assign('bb', $bb);
		$this -> display();

	}

	//更改工序状态为已经开始加工
	public function companies_process() {
		//return $this -> redirect('select_companies',array('order_id' => $order_id, 'order_sn' => $order_sn), 1, '页面跳转中');
		$order_id = $_POST['figure_number'];
		$gx_name = $_POST['gx_name'];
		$order_sn = $_POST['order_sn'];
		$processing_state = D('processing_state');
		$arr = $processing_state -> where("chart_number = '{$order_id}' and gx_name = '{$gx_name}' and order_sn = '{$order_sn}'") -> find();
		
		if ($arr['state'] == 0) {
			$sql = " UPDATE ty_processing_state SET state='1'WHERE chart_number = '{$order_id}' and gx_name = '{$gx_name}' and order_sn = '{$order_sn}' ";
			$id = $processing_state -> query($sql);
		} else {
			$sql = " UPDATE ty_processing_state SET state='2'WHERE chart_number = '{$order_id}' and gx_name = '{$gx_name}' and order_sn = '{$order_sn}' ";
			$id = $processing_state -> query($sql);
		}

		
			echo 1;
		
	}
   // 更爱工序检验报告状态
   public function inspectionSave($order_sn,$chart_number,$gx_name){
   	header("content-type:text/html;charset=utf-8");  
   	$processing_state = D("processing_state");
   	$gx_name = iconv("GB2312","UTF-8",$gx_name);
   	$arr = array('inspection' => 1 );

  	$id = $processing_state ->where("chart_number = '{$chart_number}' and order_sn  = '{$order_sn}'  and gx_name  = '{$gx_name}'") -> save($arr);
  
  	if($id){
	 				return $this -> success('提交成功', U('Admin/Order/select_companies', array('order_id' => $chart_number,'order_sn' =>$order_sn)), 3);
	 			}
   }
	// public function change_inspection($chart_number,$order_sn){
	// 			// $order_id = $_POST('figure_number');
	// 			$small_order = D('small_order');
	// 			$arr = array(
	// 				'inspection' => 1 
	// 			);
	// 			$id = $small_order -> where("chart_number = '{<1ch></1ch>art_number}'") -> save($arr);
	// 			if($id){
	// 				return $this -> success('提交成功', U('Admin/Order/select_companies', array('order_id' => $chart_number,'order_sn' =>$order_sn)), 3);
	// 			}

	// }
	//跳转到工序状态页面
	public function spik_process($order_id,$order_sn){
		return $this -> success('提交成功', U('Admin/Order/select_companies', array('order_id' => $order_id,'order_sn' =>$order_sn)), 3);
	}
	//修改订单状态为线下支付
	public function updateOrderState(){
		$order = D('order');
		$arr = array('pay_s_jj' => 4, );
		$id = $order ->where("order_sn = '{$_POST['order_sn']}'")->save($arr);
		if($id){
		echo 1;	
		}
		
			
	}
}
